#pragma once

#include <iostream>
#include <string>
#include <fstream>

class util
{
public:
    static bool ReadFileContext(const std::string &file, std::string *context)
    {
#ifdef version1
        // version1: 以文本方式读取
        std::ifstream in(file);
        if(!in.is_open()) return false;

        std::string line;
        while(std::getline(in, line)){
            *context += line;
        }

        in.close();
        return true;
#endif

#ifndef version2
#define version2
        // version2: 以二进制的方式进行文件读取，因为客户端访问的资源有可能是图片/视频
        int filesize = util::GetFileLength(file);
        if(filesize > 0)
        {
            std::ifstream in(file, std::ios::binary);
            if(!in.is_open()) return false;

            context->resize(filesize);
            in.read((char*)(context->c_str()), filesize);

            in.close();
            return true;
        }
        return false;

#endif
    }

    static bool ReadOneLine(std::string &bigstr, std::string *out, const std::string &sep)
    {
        size_t pos = bigstr.find(sep);
        if(pos == std::string::npos) return false;

        *out = bigstr.substr(0, pos);
        bigstr.erase(0, pos + sep.size());
        return true;
    }

    static std::string ReadOneLine(std::string &bigstr, const std::string &sep)
    {
       size_t pos = bigstr.find(sep);
       if(pos == std::string::npos) return std::string(); 

        std::string ret = bigstr.substr(0, pos);
        bigstr.erase(0, pos + sep.size());
        return ret;
    }

    static int GetFileLength(const std::string &filename)
    {
        std::ifstream in(filename);
        if(!in.is_open()) 
            return -1;
        
        in.seekg(0, in.end);
        int filesize = in.tellg();
        in.seekg(0, in.beg);

        in.close();
        return filesize;
    }
};